package com.webex.ta.hydra.gui.util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * Created by Cisco WebEx.
 * User: vegaz
 * Date: 2010-9-8
 * Time: 9:55:16
 */


/**
 * If you wish to have rollovers on your buttons, use this class.
 * <p/>
 * Unlike the Swing rollover support, this class works outside of
 * <code>JToolBar</code>s, and does not require undocumented client
 * property hacks or JDK1.4-specific API calls.<p>
 * <p/>
 * Note: You should not call <code>setBorder()</code> on your buttons,
 * as they probably won't work properly.
 *
 * @version $Id: RolloverButton.java 12504 2008-04-22 23:12:43Z ezust $
 */
public class RolloverButton extends JButton {
    public RolloverButton() {
        //setContentAreaFilled(true);
        addMouseListener(new MouseOverHandler());
    }


    public RolloverButton(Icon icon) {
        this();

        setIcon(icon);
    }


    public void updateUI() {
        super.updateUI();
        //setBorder(originalBorder);
        setBorderPainted(false);
        setRequestFocusEnabled(false);
        setMargin(new Insets(1, 1, 1, 1));
    }


    public void setEnabled(boolean b) {
        super.setEnabled(b);
        setBorderPainted(false);
        repaint();
    }


    public void setBorderPainted(boolean b) {
        try {
            revalidateBlocked = true;
            super.setBorderPainted(b);
            setContentAreaFilled(b);
        }
        finally {
            revalidateBlocked = false;
        }
    }


    /**
     * We block calls to revalidate() from a setBorderPainted(), for
     * performance reasons.
     */
    public void revalidate() {
        if (!revalidateBlocked)
            super.revalidate();
    }


    public void paint(Graphics g) {
        if (isEnabled())
            super.paint(g);
        else {
            Graphics2D g2 = (Graphics2D) g;
            g2.setComposite(c);
            super.paint(g2);
        }
    }


    private static final AlphaComposite c = AlphaComposite.getInstance(
            AlphaComposite.SRC_OVER, 0.5f);

    private boolean revalidateBlocked;


    class MouseOverHandler extends MouseAdapter {
        public void mouseEntered(MouseEvent e) {
            setContentAreaFilled(true);
            setBorderPainted(isEnabled());
        }

        public void mouseExited(MouseEvent e) {
            setContentAreaFilled(false);
            setBorderPainted(false);
        }
    }
}
